package com.example.chaomi;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;

/**
 * @author Giec:lijh
 *
 */
public class GiecPowerManager {
	
	private Context mContext;
	private PowerManager pm;
	private AlarmManager am;
	
	private static final String TAG = "GiecPowerManager:lijh";
	
	public GiecPowerManager(Context context) {
		this.mContext = context;
		pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
		am =(AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
	}
	public void powerOff() {
		pm.shutdown(false,false);
	}
	public void powerReboot() {
		pm.reboot("");
	}
	public void suspend() {
		pm.goToSleep(SystemClock.uptimeMillis());
	}
	public void resume() {
		pm.wakeUp(SystemClock.uptimeMillis());
	}
	/**
	 * system will suspend in suspendTime provided
	 * @param suspendTime  millisecond
	 */
	public void suspendTask(long suspendTime) {
		Log.d(TAG, "suspendTime:"+suspendTime);		
		PendingIntent pt = PendingIntent.getBroadcast(mContext, 0, new Intent("GiecSuspendTask"), 0);
		am.set(AlarmManager.RTC_WAKEUP, suspendTime, pt);
	}
	/**
	 * system will resume in resumeTime provided
	 * @param resumeTime millisecond
	 */
	public void resumeTask(long resumeTime) {
		Log.d(TAG, "resumeTime:"+resumeTime);
		PendingIntent pt = PendingIntent.getBroadcast(mContext, 0, new Intent("GiecResumeTask"), 0);
		am.set(AlarmManager.RTC_WAKEUP, resumeTime, pt);
	}
	
	public static class PMReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context paramContext, Intent paramIntent) {
			String taskType = paramIntent.getAction();
			PowerManager pManager = (PowerManager)paramContext.getSystemService(Context.POWER_SERVICE);
			Log.d(TAG, "receiver:"+taskType);
			if(taskType.equals("GiecSuspendTask"))
			{				
				pManager.goToSleep(SystemClock.uptimeMillis());
			} else if (taskType.equals("GiecResumeTask")) {
				pManager.wakeUp(SystemClock.uptimeMillis());
			}
		}
	}
}
